import React, { PureComponent } from 'react';
import { Form, Select, Input } from 'antd';
import PropTypes from 'prop-types';
const { Option } = Select;




/**
 * 品类保存表单
 */
class SaveForm extends PureComponent {

    formRef = React.createRef();

    static propTypes = {
        setForm: PropTypes.func.isRequired,
        user: PropTypes.object,
        roles: PropTypes.array.isRequired
    }

    UNSAFE_componentWillMount(){
       // 将form对象通过setForm()传递父组件
       this.props.setForm(this.formRef);
    }
    
    // initialValues不动态更新解决方式
    componentDidUpdate() {
        this.formRef.current.setFieldsValue({
            '_id': this.props.user['_id'],
            username: this.props.user.username,
            password: this.props.user.password,
            phone: this.props.user.phone,
            email: this.props.user.email,
            role_id: this.props.user.role_id,
        });
    }
    
    render() { 

        const { roles, user } = this.props;

        const formItemLayout = {
            labelCol: { span: 5 },//左侧label的宽度
            wrapperCol: { span: 18 } //右侧包裹的宽度
        };

        return (
            <Form ref={this.formRef} {...formItemLayout} >
                <Form.Item 
                name="username" 
                label="用户名"
                rules={[
                    { required: true, message: "用户名不能为空" },
                ]}
                >
                    <Input placeholder='输入用户名' />
                </Form.Item>
                {!user['_id'] && <Form.Item 
                name="password" 
                label="密码"
                rules={[
                    { required: true, message: "密码不能为空" },
                ]}
                >
                    <Input.Password placeholder='输入密码' />
                </Form.Item>}
                <Form.Item 
                name="phone" 
                label="手机号"
                rules={[
                    { required: true, message: "手机号不能为空" },
                ]}
                >
                    <Input  placeholder='输入手机号' />
                </Form.Item>
                <Form.Item 
                name="email" 
                label="邮箱"
                rules={[
                    { required: true, message: "邮箱不能为空" },
                ]}
                >
                    <Input  placeholder='输入邮箱' />
                </Form.Item>
                <Form.Item 
                name="role_id" 
                label="所属角色"
                rules={[
                    { required: true, message: "所属角色不能为空" },
                ]}
                >
                    <Select placeholder="选择角色" allowClear >   
                        { roles.map((v, i) => <Option value={v['_id']} key={i}>{v.name}</Option>)}
                    </Select>
                </Form.Item>
            </Form>
        );
    }
}
 
export default SaveForm;